using System;
using UnityEngine;

public class MusicBox : MonoBehaviour
{
	private AudioSource musicSource;

	public AudioClip[] clips;

	[SerializeField]
	private int currentIndex;

	private void Start()
	{
		musicSource = GetComponent<AudioSource>();
		PersistenData.OnMusicChange = (Action<bool>)Delegate.Combine(PersistenData.OnMusicChange, new Action<bool>(OnMusicChange));
		if (PersistenData.Music)
		{
			PlayMusic(UnityEngine.Random.Range(0, clips.Length));
		}
	}

	private void Update()
	{
		if (!musicSource.isPlaying && PersistenData.Music)
		{
			currentIndex = (currentIndex + 1) % clips.Length;
			PlayMusic(currentIndex);
		}
	}

	private void PlayMusic(int index)
	{
		currentIndex = index;
		musicSource.PlayOneShot(clips[index], 0.75f);
	}

	private void OnMusicChange(bool flag)
	{
		if (!flag)
		{
			musicSource.Stop();
		}
		else
		{
			PlayMusic(UnityEngine.Random.Range(0, clips.Length));
		}
	}
}
